package com.mf.controller.threadPool;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: lmf
 * @Create: 2025/5/28 21:51
 * @module 单例线程池
 * @Description: 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
 */
@RestController
@RequestMapping("/newSingleThreadExecutor")
public class newSingleThreadExecutor {
    @RequestMapping("/test")
    @Operation(summary = "单线程执行")
    public void test() {
        final ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            int j = i;
            threadExecutor.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "正在执行" + j);
            });
        }
        // 如果是局部线程池使用的话，需要关闭否则会造成内存泄漏
        threadExecutor.shutdown();
    }
}
